<template>
  <!-- 查询表单 -->
  <el-form
    ref="formSearchRef"
    label-width="100px"
    :inline="true"
    :model="formSearch"
    class="data-grid-search-form"
  >
    <el-row>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="业务类型">
          <el-input v-model="formSearch.category" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="手机号">
          <el-input v-model="formSearch.receiver" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item label="短信内容">
          <el-input v-model="formSearch.sendMessage" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="发送状态">
          <el-select v-model="formSearch.status" clearable>
            <el-option label="发送成功" value="1"></el-option>
            <el-option label="发送失败" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="时间从">
          <el-date-picker
            v-model="formSearch.sendTimeBegin"
            type="datetime"
            :shortcuts="shortcuts"
            clearable
            class="fix-el-date-picker-width"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="到">
          <el-date-picker
            v-model="formSearch.sendTimeEnd"
            type="datetime"
            :shortcuts="shortcuts"
            clearable
            class="fix-el-date-picker-width"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item style="float: right">
          <el-button type="primary" @click="handleSearch">查 询</el-button>
          <el-button @click="handleSearch">重 置</el-button>
          &nbsp; &nbsp;
          <el-link
            type="primary"
            :underline="false"
            @click="searchInputExpland = !searchInputExpland"
          >
            <template v-if="searchInputExpland">
              收起 &nbsp; <el-icon><arrow-up /></el-icon>
            </template>
            <template v-if="!searchInputExpland">
              展开 &nbsp; <el-icon><arrow-down /></el-icon>
            </template>
          </el-link>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <data-grid
    ref="dataGridRef"
    id="admin-sms-grid"
    row-key="smsId"
    defaultSort="descending"
    defaultSortBy="sendTime"
    :request="handleLoadGrid"
    :columns="state.columns"
    :buttons="state.buttons"
  >
    <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
    <template #button-primary="button">
      <!-- <el-button size="mini" :icon="Download">导出日志</el-button> -->
    </template>

    <template #sendMessage="slotProps">
      <el-link
        type="primary"
        @click="handleView(slotProps.row)"
        style="font-weight: normal"
        >{{ formatLogInfo(slotProps.row.sendMessage) }}</el-link
      >
    </template>

    <template #status="slotProps">
      <el-tag size="small" v-if="slotProps.row.status == 1"> 发送成功</el-tag>
      <el-tag size="small" v-if="slotProps.row.status == 0" type="warning">
        发送失败</el-tag
      >
    </template>
  </data-grid>

  <view-form ref="viewFormRef" title="短信日志"></view-form>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, onUnmounted } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import ViewForm from "./view.vue";
import { Download, ArrowDown, ArrowUp } from "@element-plus/icons-vue";
import utils from "../../../utils/utils";
import moment from "moment";
import apiSms from "../api/sms";
import bus from "../../../utils/bus";

// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const viewFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);

// 查询区域表单数据
const formSearch = reactive({
  category: "",
  receiver: "",
  sendMessage: "",
  status: "",
  // 前端控件使用
  sendTimeBegin: <Date>(<any>null),
  sendTimeEnd: <Date>(<any>null),
  // 提交后台使用
  sendTimeBeginString: "",
  sendTimeEndString: "",
});

const shortcuts = [
  {
    text: "前一星期",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      formSearch.sendTimeBegin = start;
      formSearch.sendTimeEnd = end;
      // return [start, end];
    },
  },
  {
    text: "前一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      formSearch.sendTimeBegin = start;
      formSearch.sendTimeEnd = end;
      // return [start, end];
    },
  },
  {
    text: "前三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      formSearch.sendTimeBegin = start;
      formSearch.sendTimeEnd = end;
      // return [start, end];
    },
  },
];

const state = reactive({
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      title: "业务类型",
      field: "category",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: "手机号",
      field: "receiver",
      sortable: true,
      resizable: true,
      width: 120,
    },
    {
      title: "短信内容",
      field: "sendMessage",
      sortable: true,
      resizable: "true",
      tdSlot: "sendMessage",
    },

    {
      title: "发送时间",
      field: "sendTime",
      sortable: true,
      resizable: true,
      width: 180,
    },
    {
      title: "状态",
      field: "status",
      sortable: true,
      resizable: true,
      tdSlot: "status",
      width: 150,
    },
    {
      title: "业务主键",
      field: "businessKey",
      sortable: true,
      resizable: true,
      hidden: true,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
  ],
  row: null,
});

// 加载数据
const handleLoadGrid = async (params: any) => {
  // 后台处理不了默认的时间格式，需要转换一下
  if (formSearch.sendTimeBegin != null) {
    formSearch.sendTimeBeginString = moment(formSearch.sendTimeBegin).format(
      "YYYY-MM-DD HH:mm:ss"
    );
  }
  if (formSearch.sendTimeEnd != null) {
    formSearch.sendTimeEndString = moment(formSearch.sendTimeEnd).format(
      "YYYY-MM-DD HH:mm:ss"
    );
  }

  let query = utils.serializeArray(formSearch);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiSms
    .querySmsListing(params)
    .then((respons: any) => {
      if (respons != undefined) {
        data = respons.data;
      }
    })
    .catch((err: any) => {
      utils.errorNotification("数据处理错误", err);
    });

  // 返回数据给表格组件
  return data;
};

const formatLogInfo = (cellValue: string) => {
  if (cellValue != undefined) {
    return cellValue.length > 50
      ? cellValue.substring(0, 50) + "..."
      : cellValue;
  }
  return cellValue;
};

// 打开详情页
const handleView = (row: any) => {
  viewFormRef.value.show(row);
};

// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};

onMounted(() => {
  bus.on("setting-tab-changed", (data: any) => {
    if (data.index == 4) {
      handleSearch();
    }
  });
});

onUnmounted(() => {
  bus.off("setting-tab-changed");
});
</script>
